import {Component, OnDestroy, OnInit} from '@angular/core';
import {AuthService} from '../../../services/auth.service';
import {MsgResult} from '../../../models/msg-result';
import {ActivatedRoute, Router} from '@angular/router';
import {Components, MsgConstants} from '../../../constants/constants';
import {ResponseUtil} from '../../../util/response-util';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {Dialog} from '../../../widgets/one-dialog/dialog';
import {DataStorageUtil} from '../../../util/data-storage-util';
import {OnlineService} from '../../../services/online.service';
import {AdminUtilService} from '../admin-util.service';
import {Subscription} from 'rxjs/Subscription';
import {Observable} from 'rxjs/Observable';
import {Message} from '@stomp/stompjs';
import {AlarmSubject} from '../../../util/alarm-subject';
import {AppConfig} from '../../../app.config';
import {SiteStatusSubject} from "../../../util/site-status-subject";
import {MsgSubscribeService, SubscribeConstants} from '../../../tools/msgSubscribe/msg-subscribe.service';


declare var $;

@Component({
  selector: 'app-admin-header',
  templateUrl: './admin-header.component.html',
  styleUrls: ['./admin-header.component.css']
})
export class AdminHeaderComponent implements OnInit, OnDestroy {

  myName: string;
  rabbitName: string;
  warnInfoArr: Array<any> = [];
  siteStatusArr: Array<any> = [];
  siteStatusObj: any;

  public messages: Observable<Message>;
  public mq: Array<any> = [];
  public count = 0;
  private subConstants: SubscribeConstants;
  private headStomp: any;

  private siteStatusSubscript: Subscription;


  constructor(
  private router: Router,
  private route: ActivatedRoute,
  private authService: AuthService,
  private responseUtil: ResponseUtil,
  private dataStorage: DataStorageUtil,
  private onlineService: OnlineService,
  private dialogService: OneDialogService,
  private adminUtilService: AdminUtilService,
  private siteStatusSubject: SiteStatusSubject,
  private msgSubscribeService: MsgSubscribeService,
  private alarmSubject: AlarmSubject,
  ) {
    // this.headStomp = new StompService(RabbitConfig);
    this.initObject();
  }


  ngOnInit() {
    this.getName();
    // this.subscribeData();
    this.getNationSite();
    this.subscriptStatus();
  }
  ngOnDestroy() {
    this.msgSubscribeService.unsubscribe();
  }
  /**
   * 实例化对象
   */
  initObject() {
    this.subConstants = new SubscribeConstants();
  }
  getName() {
    this.onlineService.getAccountName()
      .subscribe(
        result => this.responseUtil.success(result, this.extractAccountName),
        error => this.responseUtil.error(error)
      );
  }

  /**
   * 调用消息推送
   */
  subscribeData() {
    if ( AppConfig.enableMsgSubscribe ) {
      this.onlineService.getAccountName()
        .subscribe(
          result => this.responseUtil.success(result, () => {
            if (result && result.code === MsgConstants.MSG_CODE_OK) {
              this.rabbitName = result.data;
              this.subConstants.url = '/queue/' + this.rabbitName;
              this.subConstants.dataSubject = this.alarmSubject;
              this.subConstants.isSingle = false;
              this.subConstants.isAck = true;
              // this.subConstants.callback = this.on_next;
              this.msgSubscribeService.subscribe(this.subConstants);
              this.ngSubscribe();
            }
            if (result && result.code !== MsgConstants.MSG_CODE_OK) {
              this.dialogService.info(result.message);
            }
          }),
          error => this.responseUtil.error(error)
        );
    }
  }
  logout() {
    // 退出信息modal框
    const dialog = new Dialog();
    dialog.type = Dialog.DialogType.Info;
    dialog.isModal = true;
    dialog.title = '退出信息';
    dialog.content = '确定退出系统吗？';
    dialog.cancelBtn = '取消';
    dialog.okBtn = '确定';
    dialog.showCancelBtn = true;
    dialog.okBtnFun = this.requestLogout;
    this.dialogService.push(dialog);

  }
  /**
   * 确认退出时，回调的请求退出方法
   */
  private requestLogout = () => {
    this.authService.logout().subscribe(
      result => this.responseUtil.success(result, this.processResult),
      error => this.responseUtil.error(error)
    );
  };
  /**
   * 成功时，跳转到登录页面
   * @param result
   */

  private processResult = (result: MsgResult) => {
    this.dataStorage.clear();
    this.router.navigateByUrl(Components.authenComponent);
  };
  /**
   *跳转到个人中心页面
   */
  jumpMe() {
      this.router.navigate(['me'], { relativeTo: this.route});
  }

  /**
   * 提取账户名
   * @param result
   */
  private extractAccountName = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
       this.myName = result.data;
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 收缩报警信息
   */
  warnInfo = (elem) => {
    if ($(elem).siblings('.dropdown-menu').css('display') === 'none') {
      $(elem).siblings('.dropdown-menu').show();
    } else {
      $(elem).siblings('.dropdown-menu').hide();
    }
  };
  /**
   * 跳转到报警历史记录
   * @param elem
   */
  jumpHistoryRecord(elem) {
    $(elem).parents('.dropdown-menu').hide();
    this.warnInfoArr = [];
    this.router.navigate(['admin/msg/alarmrecord/record'], { relativeTo: this.route});
  }
  /**
   * 跳转到报警详情
   * @param elem
   * @param data
   */
  jumpRecordDetail(elem, data) {
    this.updateRecordStatus(data.contentId, data.logId);
    $(elem).parents('.dropdown-menu').hide();
  }
  /**
   * 修改报警信息状态
   * @param contentId
   * @param logId
   */
  updateRecordStatus(contentId, logId) {
    this.adminUtilService.putWarnSiteStatus(logId)
      .subscribe(
        result => this.responseUtil.success(result, () => {
          if (result && result.code === MsgConstants.MSG_CODE_OK) {
            const routerUrl = this.router.url;
            if (routerUrl.indexOf('warnType=warn') === -1) {
              this.warnInfoArr.every((data, i) => {
                if ( logId === data.logId) {
                  this.msgSubscribeService.setAckMessage(this.warnInfoArr[i].mesHeader);
                  this.warnInfoArr.splice(i, 1);
                  return false;
                }
              });
              this.alarmSubject.pushData(this.warnInfoArr);
            } else {
              this.dialogService.info('请处理当前报警信息');
            }
            this.router.navigate(['admin/msg/alarmrecord/record/deal', {id: contentId, warnType: 'warn'}], { relativeTo: this.route});
          }
          if (result && result.code !== MsgConstants.MSG_CODE_OK) {
            this.dialogService.info(result.message);
          }
        }),
        error => this.responseUtil.error(error)
     );
  }

  dropDownHide = (e) => {
    $(e.target).children('.dropdown-menu').hide();
  };

  /**
   * 获取国控站站点数据
   */
  getNationSite(){
    if (AppConfig.enableMsgSubscribe) {
      this.adminUtilService.getMapSiteData().subscribe(
        result => this.responseUtil.success(result,this.handleNationSite),
        error => this.responseUtil.error(error)
      )
    }
  }
  private handleNationSite = (result:MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (result.data.hasOwnProperty('siteList') && result.data.siteList.length > 0){
        this.siteStatusArr = [];
        this.siteStatusObj = {};
        result.data.siteList.forEach((val)=>{
          // this.siteStatusArr.push({siteCode:val.siteCode,siteStatus:false});
          this.siteStatusObj[val.siteCode] = false;
        });
        this.siteStatusSubject.pushData(this.siteStatusObj);
        this.subscribeData();
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
//  angular订阅
  ngSubscribe() {
    this.subConstants.dataSubject.subscribeData().subscribe(
      (data) => {
        this.warnInfoArr = data;
      })
  }
  subscriptStatus(){
    this.siteStatusSubscript = this.siteStatusSubject.subscribeData().subscribe((data)=>{
      // this.siteStatusArr = data;
      this.siteStatusObj = data;
    });
  }
  /** Consume a message from the _stompService */
  public on_next = (message) => {
    if (!message) {
      return false;
    }
    let mes = JSON.parse(message.body);
    mes.logId = mes.id;
    mes.mesHeader = message.headers;
    mes.client = this.headStomp.client;
    this.warnInfoArr.unshift(mes);
    let dataArr = [];
    dataArr.push(mes);
    this.alarmSubject.pushData(this.warnInfoArr);
    let cloneStatusObj = {};
    for(const key in this.siteStatusObj){
      if(this.siteStatusObj.hasOwnProperty(key)){
        cloneStatusObj[key] = this.siteStatusObj[key];
      }
    }
    if(cloneStatusObj.hasOwnProperty(mes.siteCode) && !cloneStatusObj[mes.siteCode]){
      cloneStatusObj[mes.siteCode] = true;
      this.siteStatusSubject.pushData(cloneStatusObj);
    }
  };
}
